const {userList,foodList} = require('../../analoge_data/index')
const {writeFile,readFile} = require('../../util/index')
const path = require('path')
const { stat } = require('fs')
const uuid = require('node-uuid');
// 添加数据
const writeFileFn = (writePath,userGisterData)=> {
    writeFile(writePath,JSON.stringify(userGisterData)).then(res => {
        console.log('写入数据成功')
    }).catch(err=> {
        console.log('写入失败：',err)
    })
}

// 删除数据
const delUserReject = (req,res)=> {
   let {id} = req.body
   const writePath = path.join(__dirname,'../../analoge_data/user_data.json')
    console.log('删除数据===：',req)
    readFile(writePath).then(async (data)=> {
         let readData = JSON.parse(data.toString())
         let delData = readData.filter(item => {
            return item.id !== id
        })
        console.log('删除后数据',delData)
        const tempData = await writeFile(writePath,JSON.stringify(delData))
        const result = {
            state: 200,
            msg: '删除成功',
            data: delData
        }
        res.send(result)
    }).catch(err => {
        console.log(err)
    })
}

const userReject = (req,res)=> {
    var uuid1 = uuid.v1();//v1是根据时间戳生成的 （建议使用）
    let userGisterData =  req.body // 这个是前端传来的数据
    userGisterData.id = uuid1
    // console.log('转：',insertData)
    const writePath = path.join(__dirname,'../../analoge_data/user_data.json')
    stat(writePath,function(err){
        if (err) {
            // 如果读取文件错误，说明文件还没有创建，那么我们就可以在穿件文件的同时，对数据进行处理
            writeFileFn(writePath,([userGisterData]))

        } else {
            readFile(writePath).then(res=> {
                let readData = JSON.parse(res.toString())
                console.log('读取成功：',readData)
                let content = [userGisterData,...readData]
                writeFileFn(writePath,content)
            }).catch(err => {
                console.log('读取失败：',err)
            })
        }
    })
  
    res.send({
        state: 200,
        msg: '提交成功',
        user_id: '100001'
    })
}

// 读取数据，并向前端发送数据
const getUserRegisterList = (req,res)=> {
    const writePath = path.join(__dirname,'../../analoge_data/user_data.json')
    readFile(writePath).then(data=> {
        let readData = JSON.parse(data.toString()) // 把字符流转成正常的文字
        let result = {
            state: 200,
            msg: '操作成功',
            data: readData
        }
        res.send(result)
    }).catch(err => {
        let result = {
            state: 405,
            msg: '操作失败',
            data: []
        }
        res.send(result)
        console.log('读取失败：',err)
    })

}

const getFoodList = (req,res)=> {
    let data = {
        code: 200,
        data: foodList
    }
    res.send(data)
}

const getUserList = (req,res)=> {
    console.log('请求数据：',req.query)
    let data = {
        code: 200,
        data: userList
    }
    res.send(data)
}

module.exports = {
    userReject,
    getUserList,
    getFoodList,
    getUserRegisterList,
    delUserReject
}